package com.istock.union.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.union.user.model.Constants;

@Controller
public class ImgGenerateController {

	@RequestMapping(value = "captcha/writeImage")
	public String write(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int len = 5;
		
		try {
			RandImage img = new RandImage(len);
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			BufferedImage bi = img.creatImage();

			// 存放随机码至session中
			request.getSession().setAttribute("verifyCode", img.getRandomString());
			ImageIO.write(bi, "JPEG", response.getOutputStream());
		} catch (Exception e) {
			Random random = new Random();
			request.getSession().setAttribute("verifyCode",
					"MSG_CREAGE_ERROR_" + random.nextInt(10000));
		}
		return null;
	}
	
	@RequestMapping(value="captcha/vueImage")
	@ResponseBody
	public ApiBaseResponse<String> vueImage(HttpServletRequest request){
		int len = 5;
		
		try {
			RandImage img = new RandImage(len);
			BufferedImage bi = img.creatImage();

			// 存放随机码至session中
			request.getSession().setAttribute("verifyCode", img.getRandomString());
			
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ImageIO.write(bi, "JPEG", bos);
			
			ApiBaseResponse<String> result = new ApiBaseResponse<String>(RetStatusEnum.SUCCESS , Constants.API_RESPONSE_SUCCESS_CODE,Constants.API_RESPONSE_SUCCESS_MESSAGE , 
					new String(Base64.encodeBase64(bos.toByteArray())));
			
			return result;
			
		} catch (Exception e) {
			Random random = new Random();
			request.getSession().setAttribute("verifyCode",
					"MSG_CREAGE_ERROR_" + random.nextInt(10000));
		}
		return null;
	}
}
